#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/9/25 10:57
# @Author  : 王凯
# @File    : app_login.py
# @Project : scrapy_spider
import json
import random
import time
import warnings

import requests
from loguru import logger
from retrying import retry

from apps.pdd.pdd.utils.app.core.app_verify import PddAppVerify
from utils.proxies_tools import get_company_ip_crawler_by_api

warnings.filterwarnings("ignore")

from apps.pdd.pdd.utils.js import MSG_MAP

PHONE_MODELS = [
    # ["Redmi", "M2006C3LC", "OPM1.171019.011"],
    # ["Redmi", "M2006C3LC", "QP1A.190711.020"],
    # ["HUAWEI", "ALP-AL00", "HUAWEIALP-AL00"],
    ["Pixel", "Pixel", "VC.20241119.113"],
]
PHONE_OS_VERSIONS = ["8.1.0", "9", "10", "12", "14"]
DEVICES_IDS = [
    "hKOZkhg6",
    "PQ0Va13u",
    "GmkOg8Sk",
    "huODjrIW",
    "GWo6zXbn",
    "Bup6r7Lm",
    "caobywSF",
    "U8w4p50z",
    "uL6HSYbN",
    "Xw3osKbc",
    "QxaMzkn7",
    "Kpu87XFE",
    "y4VCStSB",
    "rRyHSThh",
    "SSMfPcXh",
    "OTtzj5gl",
    "unfLQ8XP",
    "PFh6hVtU",
    "Jtgww4wM",
    "QUWdVAWf",
    "4nlqdxEY",
    "oXSpknMZ",
    "Q1wCgDK4",
    "Yo8FFxGZ",
    "wsMgWHvT",
    "sk17LgYn",
    "XIEl8sZ8",
    "l7uGymAI",
    "Y2br6O1c",
    "Fc1xE735",
    "ZhcUBLrO",
    "UY1Zky6D",
    "tMEPTWtk",
    "vOn8HuoM",
    "uB1BXqY3",
    "2EEBs2tc",
    "jf8h2gwB",
    "ZNOajZoI",
    "YQDgENmt",
    "WHO2m6lC",
    "HjSyN8QA",
    "OlLUQFbY",
    "Tv3wnwPI",
    "MxoAS5O8",
    "3DQbvJoV",
    "K2Mtxfaf",
    "N8XAfVuk",
    "32jEd3wt",
    "1Pijn8rr",
    "DgyhzwqT",
    "riCQcrlF",
    "Y16ZHGuS",
    "aStg2ZFQ",
    "lZFxV4X6",
    "QassNZfI",
    "Sc3eriJz",
    "kOKRRAMN",
    "IwBgJ40X",
    "ySwMPGoD",
    "uraOSM3E",
    "k8cCALbX",
    "hZu1q1pT",
    "t7kRLSdh",
    "qltpY0Af",
    "Jyug0emU",
    "HBgB3JHu",
    "jyHwNDjC",
    "lb4sXOFB",
    "tAmmtT25",
]
# titanId

DEVICES_IDS = [
    "FTgktFks",
    "gfi3q1wM",
    "oE1P7mZU",
    "FrG1Q4F8",
    "x3jhjBGX",
    "p2pq4LIb",
    "kO2bLkls",
]


class AppLogin(object):
    session = requests.Session()
    app_version, app_build = ("7.69.0", "0ff12749b166be42db76d5e67e5d166b00ffa930")

    def __init__(self, cookie=None, headers=None):
        self.phone_os_version = random.choice(PHONE_OS_VERSIONS)
        self.phone_brand, self.phone_model, self.phone_model_version = random.choice(PHONE_MODELS)
        self.device_id = random.choice(DEVICES_IDS)
        # self.device_id = "FTgktFks"
        # self.device_id = "gfi3q1wM"
        # self.device_id = "FrG1Q4F8"
        # self.device_id = "x3jhjBGX"
        # self.device_id = "p2pq4LIb"
        # self.device_id = "kO2bLkls"
        # self.device_id = "MxoAS5O8"
        # self.device_id = "riCQcrlF"
        # self.device_id = "NbkDEDIA"
        # self.device_id = "Bup6r7Lm"
        # self.device_id = "HBgB3JHu"
        # self.device_id = "BWkCWYvO"
        if headers:
            self.session.headers = headers
        else:
            self.session.headers = {
                "etag": self.device_id,
                "referer": "Android",
                "p-appname": "pinduoduo",
                "x-pdd-info": "bold_free%3Dfalse%26bold_product%3D%26front%3D0%26tz%3DAsia%2FShanghai",
                "x-pdd-queries": f"width=1080&height=2030&net=1&brand={self.phone_brand}&model={self.phone_model}&osv={self.phone_os_version}&appv={self.app_version}&pl=2",
                "p-proc": "main",
                "p-mediainfo": "player=2.0.4&rtc=1.0.0",
                "user-agent": f"android Mozilla/5.0 (Linux; Android {self.phone_os_version}; {self.phone_model} Build/{self.phone_model_version}; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/70.0.3538.100 Mobile Safari/537.36  phh_android_version/{self.app_version} phh_android_build/{self.app_build} phh_android_channel/gw pversion/0",
                "pdd-config": f"V4:001.{''.join([i.zfill(2) for i in self.app_version.split('.')])}",
                "multi-set": "0,1",
            }
            # headers = {
            #     # "anti-token": "2afh0N9kGamECtqV8zoLP+OT8/6NS00vnuuGNSblaFVPzPtsd0U7T4NWeRX2M5WdGUHqU3pfEjdFVr7wO0OcOCpbMBmTpZy5QTyv1ePlGGiw0Ba90Ph7M+tv0jBc1la30aBmxj9fV4b9MxV7jnFIi+DVqGM4NNx2ccZ4N13xuT1GK25GD1M6AFd3uk20wOngo3ZW9il4oUp90r69UhDHCMgpWQUVEO4Ca/hEXPCu18ITszvxYWQ2wMHfjekKCroySTfH+aAneHfdPVBapo3MmvDg1iX3bqfYdq0nKmoDvXZ15RMnyrHfv+t1/sOHx8OYj102tzwQHx8yD6JS701tOQFSgm67ZACdJNmJgcHFfFM/klXNPD3YoWWUcTdBEgWXVir7jrhufPxQFoh70I7k+KOF0QP2mQ63tiHUpiGUGuYVG/SF2vvIntiVGYAXLpVUjlW",
            #     # "lat": "CDE6GBVLNTNJ26MY7SXFIGMM6KJOSG45U5ZNBJ2FOVOH3FWUQ6FQ122455f",
            #     # "p-proc-time": "442494",
            #     # "x-b3-ptracer": "hctrue65acc5a59ac14508b9e1f63396",
            #     # "x-p-t": "t=1&x-p1-t=0",
            #     # "x-p1": "MDQwMTAxWlgzYVhOc0ItRWw3NS1qcTRtLTBmNGQtNjJuWDE5ZnFuYk04Xa5/g1uMV/nUDs4qyJeIjAwhNTMfWe/OoK9gnFdUA4kTB7DlDQ0KrVCduQ9qGTFu9gVjEJWFQMrJgA7uwguGlzoT0l19t0gmEJXl6wBr",
            # }
        self.session.proxies = get_company_ip_crawler_by_api(static=True)
        logger.debug(self.session.headers)
        logger.debug(f"设置代理 {self.session.proxies}")
        if cookie:
            self.session.cookies.update(cookie)
        else:
            self.session.get("https://api.pinduoduo.com/", verify=False)

    @retry(stop_max_attempt_number=10, wait_fixed=5000)
    def gen_anti_content(self, timestamp=int(time.time() * 1000), device_id=None):
        url = "https://sekiro.wkaanig.cn/business/invoke"
        params = {
            "group": "AntiToken",
            "sekiro_token": "c232bebc-68a8-4c3d-b310-e0d26876e58b",
            "action": "AntiTokenHandler",
            "ts": timestamp,
        }
        if device_id:
            params["device_id"] = device_id

        response = requests.get(url, params=params).json()
        logger.debug(f"获取 anti_count : {response}")
        rt = response["data"]
        return rt

    def send_sms_code(self, mobile="18888888888"):
        self.session.cookies.clear()
        url = "https://api.pinduoduo.com/api/sigerus/mobile/code/request"
        params = {"pdduid": ""}
        data = {
            "mobile": mobile,
            "app_version": self.app_version,
            "channel": self.phone_brand,
            "platform": "2",
            "country_id": "1",
            "tel_code": "86",
            # "touchevent": "{\"key\":\"fNdnx1Wu2Meta07c9sG+WREbs1ALPioxuCNKSCbpzzGU0P8wbgjTj33HFGk35k+bQFdfC5YDcoEQXJWzubsbmwn2+MGL505X/rBYaz9jLRRF8sK6r/t7XDQwJ/fyXCOD914q4I5CPlAcUsR3nOXyKHJRMdj1rsntx7/Q70KyX7Y=\",\"data\":\"mex+LlgZZHgYzgWyQIrYpj8aCxQkLrZVAb9PxHZN8h0o0/1LngJ7CQOdrK++CSfzl3jZ+RpM0j+9DNtJFC0pNxmQ85Akj2rxl1ZPK6vnDe566pzRLnKtpGBn4CRPoKgSG/BeUzS6w2sVqh5W7mdf7f8EGjdnt4DhPEi2PQNNGm2VORUqDNRof6Oa9Lt3nGuR\"}",
            # "fingerprint": "{\"key\":\"fNdnx1Wu2Meta07c9sG+WREbs1ALPioxuCNKSCbpzzGU0P8wbgjTj33HFGk35k+bQFdfC5YDcoEQXJWzubsbmwn2+MGL505X/rBYaz9jLRRF8sK6r/t7XDQwJ/fyXCOD914q4I5CPlAcUsR3nOXyKHJRMdj1rsntx7/Q70KyX7Y=\",\"data\":\"mRB5BRQM297AUt97zT02IDxpnR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C++it+9r5+rPqc7jIfzSxUoOwwat9gnvke1KOMr8y0WMfTiDAWsCsGQUzhuNEaNXSkprNudeVlgw6F0J9m2GthPuKoXMV3aoXBzG0DJCBZLhwqoD/EjtaML9s6rBYAMelfWqAMbW0zJ/z0EtgK5I=\"}",
        }
        headers = {
            **self.session.headers,
            "anti-token": self.gen_anti_content(),
        }
        resp = self.session.post(url, headers=headers, params=params, json=data)
        result = resp.json()
        logger.debug(f"发送验证码结果: {mobile} {result} {self.session.cookies.get_dict()}")
        if "mobile_des" in result and result["need_call"] is False:
            return_data = {
                "code": 200,
                "msg": "验证码发送成功",
                "error_code": None,
                "error_message": None,
                "verify_auth_token": None,
                "mobile": mobile,
            }
        else:
            return_data = {
                "code": 201,
                "msg": "验证码发送异常",
                "error_code": result.get("error_code"),
                "error_message": MSG_MAP.get(result.get("error_code"), 0),
                "verify_auth_token": result.get("verify_auth_token"),
                "mobile": mobile,
            }
        return return_data

    def verify_sms_code(self, mobile="18888888888", sms_code="123456"):
        """
        验证手机验证码
        {'_nano_fp': 'XpmaX5dyn5CJlpTqXo_Q5ij5GIQHsZYq4tFOzu3a', 'api_uid': 'CiTeiGYTi0WYaQBWC1sRAg==', 'PDDAccessToken': 'FWPIZ52ZHSSVDHVNJN2FD4O7YH72KLBROB2G6HOR2PJMV4BI5UXA1206a3a', 'acid': 'c2773fb181f75c74b9dda0e2db9dfeba'}
        正常：{'uid': 9847140310122, 'uin': 'ROGZA7R7XPMXA2IO5ES2IDNAUU_GEXDA', 'access_token': 'FWPIZ52ZHSSVDHVNJN2FD4O7YH72KLBROB2G6HOR2PJMV4BI5UXA1206a3a', 'acid': 'c2773fb181f75c74b9dda0e2db9dfeba', 'mobile_id': '7173939602209382400861', 'mobile_des': '189****1861', 'complete_newer': False}
        :param mobile:
        :param sms_code:
        :return:
        """
        headers = {
            **self.session.headers,
            "content-type": "application/json;charset=UTF-8",
            "anti-token": self.gen_anti_content(),
        }
        url = "https://api.pinduoduo.com/api/sigerus/login_mobile"
        data = {
            "mobile": mobile,
            "code": sms_code,
            "login_app_id": 5,
            "refer_page_sn": "10134",
            "login_scene": "39",
            "app_version": self.app_version,
            "channel": self.phone_brand,
            "platform": "2",
            "tel_code": "86",
            "support_enhance_type": 1,
            "country_id": "1",
            # "touchevent": "{\"key\":\"PjaOEJG41UiCLiS9fLZE3GtahHyMcM4zlIoaEf9lS0YG9oJWn175AG4lHSujZO8o2/JQ8YvcQMeUY+BhJrdOSkxPlpYh7XbwJqdlCKxQnkSiriqPHAmJe+rw6ssVqqB+ZplFDN3zNgGjzsO1mlTKy10TVdrDAkDl9baJFZfYWwo=\",\"data\":\"WV5Epouy0S7W+1axaopTIErqTpY8PI4NWdUOtygAHg0b8KikqKkdyc/NcZrb7f/15vvJA5SrV4UBAYoYLCYxPf1xinBSzD4pdP4nxzBRm4WHZVJ3/EYXtTV6qMXAe9E0J0D+hNGLRU0lLl38lWCdKHomhFnjPz982CF1X9Uc17SQ02/jLt0tDkbcLx+OgazP\"}",
            # "fingerprint": "{\"key\":\"PjaOEJG41UiCLiS9fLZE3GtahHyMcM4zlIoaEf9lS0YG9oJWn175AG4lHSujZO8o2/JQ8YvcQMeUY+BhJrdOSkxPlpYh7XbwJqdlCKxQnkSiriqPHAmJe+rw6ssVqqB+ZplFDN3zNgGjzsO1mlTKy10TVdrDAkDl9baJFZfYWwo=\",\"data\":\"h6dNSlBqDitJGfnfReTBRHtTGjZ1KiGxnkbaTyAt0Zk3A7Gtn8kjhmZrBWPjFdvUOhQBZ0Fy2vwKGYGbDQibVxeQ4pGsiSDl1EVKvisteFY+IR2tS+E4NzNu3mmHP/K6P8+baAk9+ZnXSg+Z+AF7xsFg1GZVBKd4pw1IybqrIzycaZQ1Y3weuczA+W2q7bISoUU2JcMvKeuqPGV8waIpdSELGj8odi/JGmeCOSgRuxI1Pgx9f2Te164TDgqZZ9UMqTA2By7L9ttv4wbCiZqrfJVuHCC2tytotvR6DfwOnJV2sUvxD43VZYM95ocn5Y7oYrfL/6CGDMGR9wYqIOM4gV0NTDSulIZVx9WvyWO/YV1N4nAEKixsqzDCTATiYL+3sc2kAbr7V8jNH7QhL5A4HsDzxX/gOCfcLEEkx5Qil6h+YNkZSVnf3wPnKc+18DHxF7pn+ASoMvjRGpdV6/gR8MrPngB5X9Kgpb55/3hvpap7N1M09LKcnLYqcmZptnpPfW69NENGHo7pK7snPwSmwvjz4uPm+zrLSNS5eksoNBLRFpLJfU9lxXBRDWBeRJWZmXd9kbD77waqI4t5kjORXXLs8Du/8oYTOC4rouHh14kKOznfXkRJLWbKa9BNGrmZ3Iq/nQzW+prhqtlwqfkwq7Uf4Qlijugwa5knwxjlU9AH7X+ZhpHzSOHh83Vw0HC5QFLnw6MDt4PzzJ4hlO2QE/0T2UQeiWCwd+lWgobIdz8HnvU0IiZtml6a7pc3krHpGwg7zIa0BOShV/kMejnX0tZ+lNis+psDumejqaErTmKoTyVBwF5EpTIPeLGzxZuFLBnvtimwIsw/Z3yDkuNMB2U+rP9XvQGzgbrvlXHr8RWUuf7e/t+DUo3kA1rztK/QtKxK5Uq4ITkM3XXQMCZ+YNKsrZ3M/VO0rfR+GdN6wIpt19tuakT8lDY7orq+xIUa4zbkBjoW+i1K5kmZINtbprlv+7uE12mpWPrLEM94kyh58Le4tWRBDFqcYHCVgfbTkcmHt1rstSfqxOGQcUWiqzOKlQ6BQ6qcZBbUGITijzuaRgRDtM8MlYStYFVHZFutrwjxHRLWViJQPrSr5SZpeLR2+wuCX0zFjzoQuUDljJsOGcBfycYRFJIbSmPH6g+N2P3zbY0bONQZJkedx1Tm7iOaQi5DfgAIKPk6qIxGcu30zNIsBcN6RWGHEyNZPG5rYWZ93mjau3AjPUkfbXwjqiypzDydlhJRFpZ025sQM/4=\"}",
        }
        resp = self.session.post(url, json=data, headers=headers)
        result = resp.json()
        logger.debug(f"校验验证码结果: {mobile} {sms_code} {result}")
        if "verify_auth_token" in result:
            raise Exception("登录后还需校验...")
        session_cookies = self.session.cookies.get_dict()
        logger.debug(f"session_cookies {session_cookies}")
        verify_success_cookies = {
            "api_uid": session_cookies.get("api_uid"),
            "acid": result.get("acid"),
            "PDDAccessToken": result.get("access_token"),
            "pdd_user_uin": result.get("uin"),
            "mobile_id": result.get("mobile_id"),
            "mobile_des": result.get("mobile_des"),
        }
        if result.get("uid"):
            verify_success_cookies.update({"pdd_user_id": str(result.get("uid"))})
        self.session.cookies.update(verify_success_cookies)
        if result.get("success") is False:
            return_data = {
                "code": 201,
                "msg": "验证码验证异常",
                "error_code": result.get("error_code"),
                "error_message": MSG_MAP.get(result.get("error_code"), 0),
                "mobile": mobile,
                "sms_code": sms_code,
                "cookies": None,
            }
        else:
            self.session.headers.update({"accesstoken": result.get("access_token")})
            self.session.cookies.update({"PDDAccessToken": result.get("access_token")})
            return_data = {
                "code": 200,
                "msg": "验证码验证成功",
                "error_code": None,
                "error_message": None,
                "mobile": mobile,
                "sms_code": sms_code,
                "cookies": verify_success_cookies,
                "headers": self.session.headers,
                "proxies": self.session.proxies,
            }
        logger.info(return_data)
        return return_data

    def run(self, mobile="18888888888"):
        self.run_send(mobile)
        self.run_input(mobile)

    def run_send(self, mobile):
        for _ in range(3):
            send_result = self.send_sms_code(mobile)
            if send_result["code"] == 200:
                logger.success(f"发送验证码成功 {mobile}")
                break
            else:
                logger.error(f"发送验证码失败 {mobile} {send_result}")
                verify_auth_token = send_result["verify_auth_token"]
                if verify_auth_token:
                    cookie = PddAppVerify(verify_auth_token).run()
                    if cookie is False:
                        raise Exception("滑块验证失败")
                    self.session.headers.update({"VerifyAuthToken": verify_auth_token})
                    continue
                else:
                    raise Exception("无效验证")

    def run_input(self, mobile):
        for _ in range(3):
            result = self.verify_sms_code(mobile, input("\n请输入短信验证码:"))
            if result.get("code") == 200:
                return result
            elif result.get("error_code") == 40006:
                raise Exception(result)

    def refresh_token(self):
        """
        {'server_time': 1736128218, 'access_token': '3QLWJ4UG4A5GLTNE2NYZ37N4WRFEQMLC2WBZCPDPKL66B5A2LCPA120cf59', 'uid': 6537736536271, 'uin': 'FXBXPZFNNLUQCFL2Q2Z65OVKDU_GEXDA', 'old_access_token': '2FP5B3NKBA5RCJCEGMMDH4EFCNENLMQW67OVBH4GPRKL7CR3GJ7A120cf59'}
        {'server_time': 1736134526, 'access_token': 'M6WFAMUYUJOPVIIZ32RRZVDPNVLZ3PPYGMYS7MHYYS3XJWRK4EAA1227f79', 'uid': 8702577461887, 'uin': 'JNRC7VRZM635CVCGG6OYT3IUEI_GEXDA'}
        {'error_code': 40001, 'error_msg': '验证失败'}
        """
        session_cookie = self.session.cookies.get_dict()
        pdd_user_id = session_cookie.get("pdd_user_id")
        url = "https://api.pinduoduo.com/api/galilei/refresh/token"
        params = {"pdduid": pdd_user_id}
        data = {"scene": "daily"}
        anti_token = self.gen_anti_content(device_id=self.device_id)
        headers = {
            **self.session.headers,
            "content-type": "application/json;charset=UTF-8",
            "anti-token": anti_token,
            "accesstoken": session_cookie.get("PDDAccessToken"),
        }
        resp = self.session.post(
            url,
            params=params,
            data=json.dumps(data, separators=(",", ":")),
            headers=headers,
        )
        result = resp.json()
        logger.info(f"刷新token {result}")
        if "error_code" in result:
            if result.get("error_code") == 40001:
                return False
        return result.get("access_token")  # PDDAccessToken


if __name__ == "__main__":
    ck = {
        # "api_uid": "CiT0VGd2hWqUJQCoUlHUAg==",
        # "acid": "94ef122ec37352ca60fe831c33418591",
        # "PDDAccessToken": "IIXVGDPJ64MXUTIKIKLDLVQNQ7JMX6C6D5UEFBIHPU6SI65GPG5A121f8a8",
        # "pdd_user_uin": "UA5EOBZR5JWZ6LHARTJ7D5JCA4_GEXDA",
        # "mobile_id": "8171303466018242560536",
        # "mobile_des": "177****8536",
        # "pdd_user_id": "8970420249080",
    }
    self = AppLogin()
    # mobie = input("请输入手机号:")
    res = self.run("18888888888")
    print("登录结果", res)
